<?php

namespace App\Http\Controllers\Api;

use App\Constants\CodeResponse;
use App\Constants\SearchConstants;
use App\Http\Requests\GoodsListRequest;
use App\Services\CatalogService;
use App\Services\GoodsService;
use App\Services\SearchHistoryService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class GoodsController extends ApiController
{

    public function count(): JsonResponse
    {
        $count = GoodsService::getInstance()->countGoodsOnSale();
        return $this->success($count);
     }

     public function category(Request $request): JsonResponse
     {
        $id = $request->get('id');
        $category = CatalogService::getInstance()->getById($id);
        if (is_null($category)) {
            return $this->fail(CodeResponse::PARAM_VALUE_ILLEGAL);
        }
        $parent = null;
        $children = null;
        if ($category->pid ==0) {
            $parent = $category;
            $children = CatalogService::getInstance()->getL2ListByPid($category->id);
        } else {
            $parent = CatalogService::getInstance()->getL1ById($category->pid);
            $children = CatalogService::getInstance()->getL2ListByPid($category->pid);
        }
        return $this->success([
            'currentCategory' => $category,
            'parentCategory' => $parent,
            'brotherCategory' => $children
        ]);
     }

     public function list(GoodsListRequest $request): JsonResponse
     {
         $user = Auth::guard('wx')->user();
         $userId = $user->getAuthIdentifier();
         $keyword = $request->get('keyword');
         $params = $request->all();

         if ($userId && $keyword) {
             $history = [
                'user_id' => $userId,
                 'keyword' => $keyword,
                 'from' => SearchConstants::SEARCH_HISTORY_FROM_WX
             ];
            SearchHistoryService::getInstance()->saveByUserId($history);
         }
         $columns = ['id', 'name', 'brief', 'pic_url', 'is_new', 'is_hot', 'counter_price', 'retail_price'];
         $goodsList = GoodsService::getInstance()->listGoods($params,$columns);
         $goodsList = $this->successPaginate($goodsList);
         $categoryIds = GoodsService::getInstance()->listL2Category($params);
         $categoryList = CatalogService::getInstance()->getL2ListByIds($categoryIds);
         $goodsList['filterCategoryList'] = $categoryList;
         return  $this->success($goodsList);
     }

    public function detail(Request $request)
    {
        $id = $request->get('id');

     }
}